package fourfaith.com.ff_sl21_app.utils.task;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;

import org.apache.commons.lang.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import fourfaith.com.ff_sl21_app.CommonMsgDialogActivity;
import fourfaith.com.ff_sl21_app.utils.Constants;
import fourfaith.com.ff_sl21_app.utils.JsonRequest;
import fourfaith.com.ff_sl21_app.utils.task.model.TaskDistance;
import fourfaith.com.ff_sl21_app.utils.task.model.TaskJson2001;
import fourfaith.com.ff_sl21_app.utils.task.model.TaskJson3001;
import fourfaith.com.ff_sl21_app.utils.task.model.TaskQueryJson;
import fourfaith.com.ff_sl21_app.utils.task.model.Token;
import fourfaith.com.ff_sl21_app.utils.task.model.TokenJson;

public class TaskMgr {

	public static String token = null;
	public static Context context = null;
	public static ProgressDialog progressDialog= null;
//	public static String requestUrl = null;
//	public static RequestQueue mQueue = null;
	
	public final static String query_status = "1";
	public final static String query_version = "2";
	public final static String query_remoteSet = "3";
	public final static String query_alarmSet = "4";
	
	private static JsonRequest<TaskJson2001> json2001Request;

	public static JSONObject stsmtaskObj;
	public static int packettype;
	private static Map<String,String> factorNameMap = new HashMap<>();

	private TaskMgr() {}
	
	private static final TaskMgr taskMsg = new TaskMgr();
	
	public static TaskMgr getInstance(Context context) {
		TaskMgr.context = context;
		return taskMsg;
	}
	
	/**
	 * 获取token
	 * @param stcd 
	 */
	public void getToken (final String queryCode, final String stcd){
		
		Gson gson = new Gson();
		String authUrl = Constants.centerUrl;
		
		Token tj = new Token();
		tj.setIdentity("13246515");
		TokenJson tokj = new TokenJson();
		
		tokj.setType(1001);
		tokj.setToken("null");
		tokj.setSecureflag(0);
		tokj.setPayload(tj);
		String url = gson.toJson(tokj);//
		//对json串进行URLEncode编码
		String strURL = null;
		try {
			strURL = URLEncoder.encode(url, "utf-8").replace("*","*").replace("~", "~").replace("+"," ");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		authUrl = authUrl+strURL;
		
		RequestQueue mQueue = Volley.newRequestQueue(context);
		
		/**  同步  */
//		new Thread(){  
//			   @Override  
//			   public void run()  
//			   {  
//			   //把网络访问的代码放在这里     
//				   RequestFuture<String> future = RequestFuture.newFuture();
//					StringRequest stringRequest = new StringRequest(Request.Method.GET, requestUrl, future, future);
//					mQueue.add(stringRequest);
//					try {
//					Object result = future.get();
//					Object result2 = future.get(20 * 1000, TimeUnit.MILLISECONDS);
//					System.out.println(result);
//					 } catch (InterruptedException e) {
//					 e.printStackTrace();
//					 } catch (ExecutionException e) {
//					 e.printStackTrace();
//					 }catch (TimeoutException e) {
//						e.printStackTrace();
//					}
//			  }  
//		}.start();  
		
		 /**  异步  */
		JsonRequest<TaskJson3001> gsonRequest = new JsonRequest<>(Method.GET, authUrl, TaskJson3001.class,
				new Response.Listener<TaskJson3001>() {
					@Override
					public void onResponse(TaskJson3001 tk) {

						String token = tk.getPayload().get("token").toString();
						TaskMgr.token = token;
						int rspCode = tk.getRspcode();
//						System.out.println(token);
//						System.out.println(rspCode);
						if(rspCode!=0){
//							throw new ConnectException();
						}
						
						if(queryCode.equals(query_status)){
							getStatus(stcd);
						}else if(queryCode.equals(query_version)){
							getVersion(stcd);
						}else if(queryCode.equals(query_remoteSet)){
							getSetInfo(stcd);
						}else if(queryCode.equals(query_alarmSet)){
							getAlarmSetInfo(stcd);
						}
						
					}

				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						dismissProgressDialog();
						if (error.networkResponse == null) {
							Toast.makeText(context,
									"连接超时，请求不到网络数据", Toast.LENGTH_SHORT).show();
						} else {
							Toast.makeText(context,
									"发生未知错误,请稍候再试!", Toast.LENGTH_SHORT).show();
						}

					}
				});
		mQueue.add(gsonRequest);
	}
	
	/**
	 * 获取版本
	 */
	public void getVersion(final String stcd){
		
		showProgressDialog();
		
		if(token == null){
    		getToken(query_version, stcd);
    	}else{
    		TaskQueryJson deviceJson = new TaskQueryJson();
            deviceJson.setDeviceCode(stcd);
            deviceJson.setFunCode(Constants.readVersonStatus);
            deviceJson.setRequest("");
            
            TaskJson2001 json = get2001TaskJson();
    	    json.setPayload(deviceJson);
    	    
    	    pushQueryTask(json, stcd);
    	}
        
	}
	
	
	/**
	 * 获取状态
	 */
	public void getStatus(final String stcd){

		showProgressDialog();
		
		if(token == null){
    		getToken(query_status, stcd);
    	}else{
    		String requestContent = "";


			for (Map.Entry<String,Object> entry: stsmtaskObj.entrySet()){

				JSONObject model = (JSONObject) entry.getValue();
				String code = String.valueOf(packettype==1?model.get("hexCode"):model.get("asciiCode"));
				requestContent += code+"\r";

				factorNameMap.put(code,String.valueOf(model.get("name")));
			}

    		TaskQueryJson deviceJson = new TaskQueryJson();
            deviceJson.setDeviceCode(stcd);
            deviceJson.setFunCode(Constants.readFactory);
            deviceJson.setRequest(requestContent);
            
            TaskJson2001 json = get2001TaskJson();
    	    json.setPayload(deviceJson);
    	    
    	    pushQueryTask(json, stcd);
    	}
        
		
	}
	
	/**
	 * 获取远程配置信息
	 */
	public void getSetInfo(final String stcd){
		
		showProgressDialog();
		
		if(token == null){
			getToken(query_remoteSet, stcd);
		}else{
			String requestContent = "01\r03\r0F\r0C\r04\r06\r08\r0A";
			
			TaskQueryJson deviceJson = new TaskQueryJson();
			deviceJson.setDeviceCode(stcd);
			deviceJson.setFunCode(Constants.readDistanceConfig);
			deviceJson.setRequest(requestContent);
			
			TaskJson2001 json = get2001TaskJson();
			json.setPayload(deviceJson);
			
			pushQueryTask(json, stcd);
		}
		
	}
	public void releaseSetInfo(final String stcd){
		showProgressDialog();
		
		if(token == null){
			getToken(query_remoteSet, stcd);
		}
	}
	
	/**
	 * 获取报警设置信息
	 * @param stcd
	 */
	public void getAlarmSetInfo(String stcd) {
		
		showProgressDialog();
		
		if(token == null){
			getToken(query_alarmSet, stcd);
		}else{
			String requestContent = "27\r38";
			
			TaskQueryJson deviceJson = new TaskQueryJson();
			deviceJson.setDeviceCode(stcd);
			deviceJson.setFunCode(Constants.readAlarmSetting);
			deviceJson.setRequest(requestContent);
			
			TaskJson2001 json = get2001TaskJson();
			json.setPayload(deviceJson);
			
			pushQueryTask(json, stcd);
		}
		
	}
	
	/**
	 * 添加查询任务
	 * @param json
	 * @param stcd
	 */
	private void pushQueryTask(final TaskJson2001 json, final String stcd){
		
		Gson gson = new Gson();
	    //拼接要发送的json串
	    String urls = gson.toJson(json);//使用gson 转对象的时候是不会转小写,json-lib会
	 	String strURL = null;
		try {
			strURL = URLEncoder.encode(urls, "utf-8").replace("*","*").replace("~", "~").replace("+"," ");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	    
		String newUr  = Constants.centerUrl + strURL;
				
		RequestQueue mQueue = Volley.newRequestQueue(context);
		
		json2001Request = new JsonRequest<>(Method.GET, newUr, TaskJson2001.class,
				new Response.Listener<TaskJson2001>() {
					@Override
					public void onResponse(TaskJson2001 tk) {

						dismissProgressDialog();
						
						if(tk.getRspcode()==0){
							String results = tk.getPayload().getResult();
							if(results.equals("offLine")){
								showCommonMsgDialog("提示信息", "该设备不在线，无法进行查询，请刷新后再试");
							}else if(results.equals("timeOut")){
								showCommonMsgDialog("提示信息", "网络不稳定");
							}else{
								
								String funCode = json.getPayload().getFunCode();
								
								if(funCode.equals(Constants.readVersonStatus)){
									showCommonMsgDialog("版本信息", results);
								}else if(funCode.equals(Constants.readFactory)){
									//status
									String requestContent = json.getPayload().getRequest();
									String[] requestArray = requestContent.split("\\r");
									String[] valueArray = results.split("\\r");

									StringBuilder resultSb = new StringBuilder();
									for (int i = 0; i < requestArray.length; i++) {
										boolean isFirst = true;
										String factorCode = requestArray[i];
										for (int j = 0; j < valueArray.length; j++) {
										    if(valueArray[j].contains(requestArray[i])){
										    	if(!isFirst)
														resultSb.append("\n");
										    	String[] split = valueArray[j].split("_");
										    	String value = "";
										    	if(split.length>1){
										    		value = split[1];

										    	}else{
										    		value = "未接入";
										    	}
										    	if(factorNameMap.containsKey(factorCode)){
													if(resultSb.length()>0)
														resultSb.append("\n");
													String name = factorNameMap.get(factorCode);
													resultSb.append(name);
													resultSb.append(":");
													resultSb.append(value);
										    	}
										    	if(isFirst)
										    		isFirst = false;
										     break;
										    }
										    if(j==valueArray.length-1){
                                                String value = "未接入";
                                                if(factorNameMap.containsKey(factorCode)){
                                                    if(resultSb.length()>0)
                                                        resultSb.append("\n");
                                                    String name = factorNameMap.get(factorCode);
                                                    resultSb.append(name);
                                                    resultSb.append(":");
                                                    resultSb.append(value);
                                                }
                                            }
									   }
									}
									
									showCommonMsgDialog("状态信息", resultSb.toString());
									
								}else if(funCode.equals(Constants.readDistanceConfig)){
									
									TaskDistance distance = TaskDistance.getTaskDistanceByStr(results);
									if(distance != null){
										
										StringBuilder resultSb = new StringBuilder();
										Map<Integer, String> typeMap = TaskDistance.getTypeMap();
										resultSb.append("中心站地址:");
										resultSb.append(distance.getCenterAddress());
										resultSb.append("\n");
										resultSb.append("通信密码:");
										resultSb.append(distance.getPwd());
										resultSb.append("\n");
										resultSb.append("通信号码:");
										resultSb.append(distance.getNumber());
										resultSb.append("\n");
										resultSb.append("中心站1信道类型:");
										resultSb.append(typeMap.get(Integer.parseInt(distance.getMain1Type())));
										resultSb.append("\n");
										resultSb.append("中心站1信道地址:");
										resultSb.append(distance.getMain1Address());
										
										showCommonMsgDialog("配置信息", resultSb.toString());
										
//										Intent intent = new Intent(context,DistanceDialogActivity.class);
//										intent.putExtra("distance", JSONObject.toJSONString(distance));
//										context.startActivity(intent);
										
									}else{
										showCommonMsgDialog("查询信息", "返回结果为空");
									}
									
								} else if(funCode.equals(Constants.readAlarmSetting)){
									String rain = "终端未设置";
									String water = "终端未设置";
									
									String requestContent = json.getPayload().getRequest();
									String[] requestArray = requestContent.split("\\r");
									String[] valueArray = results.split("\\r");
									
									for(int i=0;i<valueArray.length;i++){
										String[] split = valueArray[i].split("_");
											switch (split[0]) {
												case "27"://降水量
													if(split.length>1){
														if(StringUtils.isNotEmpty(split[1]))
														 rain = split[1];
													}
													break;
							                    case "38"://水位
							                    	if(split.length>1){
							                    		if(StringUtils.isNotEmpty(split[1]))
							                    		water = split[1];
							                    	}
													break;
												default:
													break;
											}
									}
									
									StringBuilder resultSb = new StringBuilder();
									resultSb.append("降水量(mm)：");
									resultSb.append(rain);
									resultSb.append("\n");
									resultSb.append("水位(m)：");
									resultSb.append(water);
									showCommonMsgDialog("状态信息", resultSb.toString());
									
								}
								else {
									//解析发送回来的内容
									showCommonMsgDialog("查询信息", results);
								}
								
								
							}
						}else if(tk.getRspcode()==2){
							token = null;
							getToken(query_version, stcd);
						}else{
							getToken(query_version, stcd);
							//showCommonMsgDialog("提示信息", "TOKEN无效,请刷新页面");
						}
						
					}

				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						dismissProgressDialog();
						if (error.networkResponse == null) {
							Toast.makeText(context,
									"连接超时，请求不到网络数据", Toast.LENGTH_SHORT).show();
						} else {
							Toast.makeText(context,
									"发生未知错误,请稍候再试!", Toast.LENGTH_SHORT).show();
						}

					}
				});
		mQueue.add(json2001Request);
	}
	
	/**
	 * 添加下发任务
	 * @param json
	 * @param stcd
	 */
	private void pushReleaseTask(final TaskJson3001 json, final String stcd){
		
		Gson gson = new Gson();
		//拼接要发送的json串
		String urls = gson.toJson(json);//使用gson 转对象的时候是不会转小写,json-lib会
		String strURL = null;
		try {
			strURL = URLEncoder.encode(urls, "utf-8").replace("*","*").replace("~", "~").replace("+"," ");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		String newUr  = Constants.centerUrl + strURL;
		
		RequestQueue mQueue = Volley.newRequestQueue(context);
		
		JsonRequest<TaskJson3001> gsonRequest = new JsonRequest<TaskJson3001>(Method.GET, newUr, TaskJson3001.class,
				new Response.Listener<TaskJson3001>() {
			@Override
			public void onResponse(TaskJson3001 tk) {
				
				dismissProgressDialog();
				
				if(tk.getRspcode()==0){
					String re = tk.getPayload().get("Result").toString();
					if(re.equals("1.0")){
						showCommonMsgDialog("提示信息", "命令下发成功,请稍候查询结果");
					}else{
						showCommonMsgDialog("提示信息", "任务下发失败");
					}
				}else if(tk.getRspcode()==2){
					//token 过期，重新获取token,在请求一次
					token = null;
//					getVersion(stcd);
				}else{
					showCommonMsgDialog("提示信息", "TOKEN无效,请刷新页面");
				}
				
			}
			
		}, new Response.ErrorListener() {
			
			@Override
			public void onErrorResponse(VolleyError error) {
				dismissProgressDialog();
				if (error.networkResponse == null) {
					Toast.makeText(context,
							"连接超时，请求不到网络数据", Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(context,
							"发生未知错误,请稍候再试!", Toast.LENGTH_SHORT).show();
				}
				
			}
		});
		mQueue.add(gsonRequest);
	}
	
	/**
	 * 显示公用提示dialog
	 * @param title
	 * @param content
	 */
	private void showCommonMsgDialog(String title, String content){
		Intent intent = new Intent(context,CommonMsgDialogActivity.class);
		intent.putExtra("title", title);
		intent.putExtra("content", content);
		context.startActivity(intent);
	}
	
	public static void showProgressDialog(){
		if(context != null){
			if (progressDialog == null || (progressDialog != null && !progressDialog.isShowing())) {
//				progressDialog = ProgressDialog.show(context, "", "正在查询...",true);
				
				progressDialog = new ProgressDialog(context);
		        //设置ProgressDialog 的一个Button  
		        progressDialog.setButton(DialogInterface.BUTTON_POSITIVE,"取消", new DialogInterface.OnClickListener(){
					@Override
					public void onClick(DialogInterface dialog, int which) {
						json2001Request.cancel();
						progressDialog.dismiss(); 
					}
		        });  
		        // 设置进度条风格，风格为圆形，旋转的  
		        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);  
		        // 设置ProgressDialog 标题  
		        progressDialog.setTitle("");  
		        // 设置ProgressDialog 提示信息  
		        progressDialog.setMessage("正在查询...");  
		        // 设置ProgressDialog 的进度条是否不明确  
		        progressDialog.setIndeterminate(true);           
		        // 设置ProgressDialog 是否可以按退回按键取消  
		        progressDialog.setCancelable(false);      
		        progressDialog.show();
				
			}
		}
	}
	private void dismissProgressDialog(){
		if(context != null){
			if( progressDialog!=null && progressDialog.isShowing()){ 
				progressDialog.dismiss(); }
		}
	}
	
	private static TaskJson2001 get2001TaskJson(){
		TaskJson2001 json = new TaskJson2001();
        json.setType(2001);
		json.setSecureflag(0);
        json.setToken(token);
        return json;
	}
	
	public static TaskJson3001 get3001TaskBean(){
		TaskJson3001 json = new TaskJson3001();
		json.setType(3001);
		json.setSecureflag(0);
		json.setToken(token);
		return json;
	}

}
